package fi.tikesos.validator;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

import fi.tikesos.validator.datatype.Document;
import fi.tikesos.validator.datatype.ValidationResult;
import fi.tikesos.validator.jena.JenaRDFValidatorImpl;

@WebService(serviceName = "ValidationService", targetNamespace = Namespace.rrv)
public class ValidationService {
	@WebMethod(operationName = "ValidateRDFDocument")
	@WebResult(name = "ValidationResult", targetNamespace = Namespace.rrv)
	public ValidationResult validateRDFDocument(
			@WebParam(name = "Schema", targetNamespace = Namespace.rrv) List<Document> schema,
			@WebParam(name = "Document", targetNamespace = Namespace.rrv) Document document) {
		// Create new validator
		RDFValidator validator = new JenaRDFValidatorImpl();
		// Use provided schema(s)
		ValidationResult validationResult = null;
		try {
			for (Document s : schema) {
				InputStream is = documentToInputStream(s);
				validator.addSchema(is, s.getContentType());
				try {
					// Free resources
					is.close();
				} catch (Exception exception) {
					// Ignore exception
				}
			}
			// Validate document
			InputStream is = documentToInputStream(document);
			validationResult = validator.validate(is, document
					.getContentType());
			try {
				// Free resources
				is.close();
			} catch (Exception exception) {
				// Ignore exception
			}
		} catch (Exception exception) {
			validationResult = new ValidationResult();
			validationResult.setStatusCode("FATAL");
			validationResult.setErrorGraph(exception.toString());
		}
		return validationResult;
	}

	private static InputStream documentToInputStream(Document document)
			throws URISyntaxException, IOException {
		InputStream is = null;

		if (document.getContentURI() != null
				&& document.getContentURI().isEmpty() == false) {
			// Load from URI
			URL uri = new URL(document.getContentURI());
			//URI uri = new URI(document.getContentURI());
			String scheme = uri.getProtocol(); // .getScheme();
			if ("http".equalsIgnoreCase(scheme) == false
					&& "https".equalsIgnoreCase(scheme) == false) {
				throw new IllegalArgumentException(document.getContentURI()
						+" - "+uri.getProtocol()+" : unsupported scheme");
			}
//			if (uri. .isAbsolute() == false) {
//				throw new IllegalArgumentException(document.getContentURI()
//						+ " - not an absolute uri");
//			}
			// Open as file
			//File file = new File(uri);
			is = uri.openStream(); // new FileInputStream(file);
		} else {
			// Use content
			is = new ByteArrayInputStream(document.getContent().getBytes());
		}
		return is;
	}
}
